package org.easy.http.client.http;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.easy.http.client.ex.HttpClientException;
import org.easy.http.client.util.Utils;

import java.io.File;
import java.io.InputStream;

/**
 * @Description TODO
 * @Author WuXueLi
 * @Date 19:01 2023/2/25
 * @Version 1.0
 **/
public class FileWrapper {

    private File file;

    private String fileName;

    private InputStream content;

    private MediaType mediaType;

    public FileWrapper (Builder builder) {
        this.file = builder.file;
        this.fileName = builder.fileName;
        this.content = builder.content;
        this.mediaType = builder.mediaType;
    }

    public static Builder create () {
        return new Builder();
    }

    public RequestBody requestBody() {
        if (this.file != null) {
            return new FileRequestBody(this.file, this.mediaType);
        }
        return new InputStreamRequestBody(this.content, this.mediaType);
    }


    public String getFileName () {
        return this.fileName;
    }

    public static class Builder {

        private File file;

        private String fileName;

        private InputStream content;

        private MediaType mediaType;

        public Builder file (File file) {

            if (!file.exists()) {
                throw new HttpClientException("File Does Not Exit");
            }

            this.file = file;
            return this;
        }

        public Builder fileName (String fileName) {
            this.fileName = fileName;
            return this;
        }

        public Builder stream (InputStream stream) {
            this.content = stream;
            return this;
        }

        public Builder contentType (String contentType) {
            this.mediaType = MediaType.parse(contentType);
            return this;
        }

        public Builder mediaType (MediaType mediaType) {
            this.mediaType = mediaType;
            return this;
        }

        public FileWrapper build () {
            if (this.file != null) {
                if (this.fileName == null) {
                    this.fileName = file.getName();
                }
            } else if (this.content != null) {
                if (this.fileName == null) {
                    throw new HttpClientException("Filename may not be null");
                }
            } else {
                throw new HttpClientException("The content is null.");
            }
            if (this.mediaType == null) {
                this.mediaType = Utils.guessMediaType(this.fileName);
            }
            return new FileWrapper(this);
        }

    }

}
